//
//  KRRecipeInfoController.m
//  cookBook
//
//  Created by kuroken on 16/1/23.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRRecipeInfoController.h"
#import <SVProgressHUD.h>
#import <MJExtension.h>
#import <UITableView+FDTemplateLayoutCell.h>
#import "KRHttpRecipeTool.h"
#import "KRConst.h"
#import "KRRecipeInfo.h"
#import "KRRecipeIntroCell.h"
#import "KRStuffInfoCell.h"
#import "KRStepsCell.h"
#import "KRNoNetCell.h"

@interface KRRecipeInfoController () <KRRecipeIntroCellDelegate>
@property (nonatomic, strong) KRRecipeInfo *recipeInfo;
/** 当前请求 */
@property (nonatomic, weak) NSURLSessionDataTask *currentDataTask;
@property (nonatomic, assign, getter=isError) BOOL error;
@end

@implementation KRRecipeInfoController

- (instancetype)init
{
    if (self = [super initWithStyle:UITableViewStyleGrouped]) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _cellHeight = 0;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerClass:[KRRecipeIntroCell class] forCellReuseIdentifier:@"recipeIntro"];
    [self.tableView registerClass:[KRStuffInfoCell class] forCellReuseIdentifier:@"stuffInfo"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"other"];
    [self.tableView registerClass:[KRStepsCell class] forCellReuseIdentifier:@"step"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tip"];

    /* 加载数据 */
    [self loadData];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!self.recipeInfo) {
        // 显示指示器
        [SVProgressHUD show];
        self.tableView.userInteractionEnabled = NO;
        self.tableView.scrollEnabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.currentDataTask cancel];
    self.currentDataTask = nil;
    [SVProgressHUD dismiss];
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
}

/**
 *  加载数据
 */
- (void)loadData
{
    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRInfoGetInfo;
        requestParams[@"rid"] = self.recipeID;

    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;

        self.error = NO;
        self.tableView.scrollEnabled = YES;

        self.recipeInfo = [KRRecipeInfo mj_objectWithKeyValues:json[@"result"][@"info"]];
        [self.tableView reloadData];
        
        // 移除蒙板
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;

        self.error = YES;
        [self.tableView reloadData];
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"网络繁忙"];
        });
        KRLog(@"%@, %@", self, error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.isError) return 1; // 请求失败
    if (!self.recipeInfo) return 0;
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isError) return 1; // 请求失败
    if (section == 0 || section == 3) {
        return 1;
    } else if (section == 1) {
        return self.recipeInfo.stuffArray.count + 2;
    } else if (section == 2) {
        return self.recipeInfo.stepArray.count;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isError) {
        KRNoNetCell *cell = [KRNoNetCell cellWithTableView:tableView];
        [cell setNoNetHint:@"请求超时"];
        return cell;
    }
    
    if (indexPath.section == 0) { // 食谱简介
        KRRecipeIntroCell *cell = [KRRecipeIntroCell cellWithTableView:tableView];
        cell.delegate = self;
        cell.recipeInfo = self.recipeInfo;
        return cell;
    } else if (indexPath.section == 1) { // 食材
        if (indexPath.row < self.recipeInfo.stuffArray.count) {
            KRStuffInfoCell *cell = [KRStuffInfoCell cellWithTableView:tableView];
            cell.stuff = self.recipeInfo.stuffArray[indexPath.row];
            return cell;
        } else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"other"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"other"];
            }
            if (indexPath.row == self.recipeInfo.stuffArray.count) {
                [cell.textLabel setText:[NSString stringWithFormat:@"  制作时间:%@", self.recipeInfo.cookTime]];
            } else {
                [cell.textLabel setText:[NSString stringWithFormat:@"  用餐人数:%@", self.recipeInfo.userCount]];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    } else if (indexPath.section == 2) { // 步骤
        KRStepsCell *cell = [KRStepsCell cellWithTableView:tableView];
        cell.step = self.recipeInfo.stepArray[indexPath.row];
        cell.step_num = indexPath.row;
        return cell;
    } else if (indexPath.section == 3) { // 小贴士
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tip"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tip"];
        }
        [cell.textLabel setText:self.recipeInfo.tips.length ? self.recipeInfo.tips : @"无"];
        [cell.textLabel setFont:[UIFont systemFontOfSize:18]];
        [cell.textLabel setNumberOfLines:0];
//        [cell.textLabel setBackgroundColor:[UIColor redColor]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    return nil;
}

#pragma mark - KRRecipeIntroCellDelegate
- (void)recipeIntroCellDidClickUnfoldBtn:(UIButton *)btn addHeight:(CGFloat)height
{
    _cellHeight += height;
    [self.tableView reloadData];
}

/** KRRecipeIntroCell的高度 */
CGFloat _cellHeight;

/**
 *  计算KRRecipeIntroCell的高度
 */
- (void)setCellHeightWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath
{
    _cellHeight = [tableView fd_heightForCellWithIdentifier:@"recipeIntro" cacheByIndexPath:indexPath configuration:^(KRRecipeIntroCell *cell) {
        cell.recipeInfo = self.recipeInfo;
    }];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) return [UIScreen mainScreen].bounds.size.height - KRTopBarHeight;
    
    if (indexPath.section == 0) { // 食谱简介
        if (!_cellHeight) {
            [self setCellHeightWithTableView:tableView indexPath:indexPath];
        }
        return _cellHeight;
    } else if (indexPath.section == 1) {  // 食材
        return 44;
    } else if (indexPath.section == 2) { // 步骤
        return [tableView fd_heightForCellWithIdentifier:@"step" cacheByIndexPath:indexPath configuration:^(KRStepsCell *cell) {
            cell.step = self.recipeInfo.stepArray[indexPath.row];
            cell.step_num = indexPath.row;
        }];
    } else if (indexPath.section == 3) { // 小贴士
        CGFloat paddding = 15;
        CGFloat tipWeight = KRScreenWidth - paddding * 2;
        CGFloat tipHeight = [self.recipeInfo.tips sizeWithFont:[UIFont systemFontOfSize:18] maxW:tipWeight].height;
        return tipHeight + paddding * 2;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) {
        self.error = NO;
        [self.tableView reloadData];
        [self loadData];
        return;
    }
}
/**
 *  每组头部标题
 */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) return nil;
    
    UILabel *headerLable = [[UILabel alloc] init];
    [headerLable setTextColor:KRColor(111, 143, 18)];
    [headerLable setFont:[UIFont systemFontOfSize:20]];
    [headerLable setBackgroundColor:[UIColor whiteColor]];
    if (section == 1) {
        [headerLable setText:@"    食材"];
    } else if (section == 2) {
        [headerLable setText:@"    步骤"];
    } else if (section == 3) {
        [headerLable setText:@"    小贴士"];
    } else if (section == 4) {
        [headerLable setText:@"    评论"];
    }
    
    return headerLable;
}

/**
 *  每组头部的高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) return 0.001;

    return 50;
}

/**
 *  每组尾部的高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}

@end